<template>
    <div class="bg-white px-3" style="margin: -20px; margin-top:-1rem; margin-bottom: 0!important;">
        <el-tabs v-model="tabIndex" @tab-click="handleClick" class="ml-1">
            <el-tab-pane v-for="(tab, tabI) in tabBars" :key="tabI" :label="tab.name">
                <!-- 标签页的内容
                <button-search ref="buttonSearch" placeholder="要搜索的订单编号" @search="searchEvent">
                    会匹配和使用到slot name=left的插槽
                    <template #left>
                       左边的插槽 -->
                <!-- <router-link :to="{path:'/order/order/create'}">
                            <el-button type="success" size="mini" style="margin-right: 3px;">发布商品</el-button>
                        </router-link> 
                        <el-button type="warning" size="mini">导出数据</el-button>
                        <el-button type="danger" size="mini">批量删除</el-button>
                    </template>
高级搜索的表单
<template #form>
                         表单 
                        <el-form inline ref="form" :model="form" label-width="70px">
                            <el-form-item label="订单编号" class="mb-0">
                                <el-input v-model="form.code" size="mini" placeholder="输入商品名称">

                                </el-input>
                            </el-form-item>
                            <el-form-item label="订单状态" class="mb-0">
                                <el-select v-model="form.type" style="height: 28px; line-height: 28px;"
                                    placeholder="选择订单状态">
                                    <el-option label="区域一" value="shanghai">

                                    </el-option>
                                    <el-option label="区域二" value="beijing">

                                    </el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item label="下单时间" class="mb-0">
                                <el-date-picker size='middle' v-model='form.time' type='daterange' range-separator='至'
                                    start-placeholder='开始日期' end-placeholder='结束日期'>
                                </el-date-picker>
                            </el-form-item>

                            <el-form-item label="收货人" class="mb-0">
                                <el-input v-model="form.name" size="mini">

                                </el-input>
                            </el-form-item>
                            <el-form-item label="手机号" class="mb-0">
                                <el-input v-model="form.phone" size="mini">

                                </el-input>
                            </el-form-item>
                            <el-form-item>
                                <el-button type="info" size="mini" @click="searchEvent">搜索</el-button>
                                <el-button size="mini" @click="clearSearch">清空筛选条件</el-button>
                            </el-form-item>
                        </el-form>
                    </template>
</button-search>
商品列表
<el-table :data="tableData[tabI].list" style="border: 1px; margin-top: 20px; background-color: antiquewhite;"
    @selection-change="handleSelectionChange">
    添加顶部间距
    <el-table-column type="selection" width="45" style="align-items: center;" />
    <el-table-column label="商品信息" width="230">
        <template slot-scope="scope">
                            <div class="d-flex">
                                <div style='flex:1'>
                                    <p class="mb-1">订单编号</p>
                                    <span class="mb-1"><small>612849827649</small></span>
                                </div>
                                <div style='flex:1'>
                                    <p class="mb-1">下单时间</p>
                                    <span class="mb-1"><small>6128498276497</small></span>
                                </div>
                            </div>
                            <div class="media">
                                <img :src="scope.row.cover" style="width:60px; height:60px" class="mr-3" alt="...">
                                <div class="media-body">
                                    <a class="mt-0 text-primary"> {{ scope.row.title }}</a>
                                </div>
                            </div>
                        </template>
    </el-table-column>
    <el-table-column label="实付款" width='120' align="center">
        <template slot-scope="">
                            <span>￥20</span>
                            <p>(含运费￥0.00)</p>
                        </template>
    </el-table-column>
    <el-table-column prop="sale_count" label="买家" width='120' align="center">
        <template slot-scope="">
                            <span>用户名</span>
                            <p>(用户id：111)</p>
                        </template>
    </el-table-column>
    <el-table-column label="商品状态" align="center">
        <template slot-scope="">
                            <span class="badge badge-success">微信支付</span>
                        </template>
    </el-table-column>

    <el-table-column prop="stock" label="配送方式" align="center">顺丰快递</el-table-column>
    <el-table-column prop="price" label="交易状态" align="center">
        <template slot-scope="">
                            <div>付款状态：<span class="badge badge-success">已付款</span></div>
                            <div>发货状态：<span class="badge badge-success">待发货</span></div>
                            <div>收货状态：<span class="badge badge-success">待收货</span></div>
                        </template>
    </el-table-column>
    <el-table-column prop="ischeck" label="操作" align="center" width="150">
        <template>
                           slot-scope="scope"创建了一个名为scope的新作用域，
                             它包含了子组件传递给插槽的所有数据。然后我们可以使用v-for指令来遍历scope.items。 
                            <el-button type="primary" size="mini" plain>订单详情</el-button>
                        </template>
    </el-table-column>
</el-table>
底部
<div style="height: 60px;">
    <el-footer class="border-top d-flex align-items-center px-0 position-fixed bg-white"
        style="bottom:0;left: 200px;right: 0; z-index: 100;">
        flex:1占剩余的所有空间
        <div style="flex: 1;">
            <el-pagination :current-change="tableData[tabI].currentPage" :page-sizes="[100, 200, 300, 400]"
                :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="400">
            </el-pagination>
        </div>

    </el-footer>
</div> -->

            </el-tab-pane>
        </el-tabs>

        <!-- 高级搜索-->
        <button-search ref="buttonSearch" placeholder="要搜索的订单编号" @search="searchEvent">
            <!-- 会匹配和使用到slot name=left的插槽 -->
            <template #left>
                <!-- 左边的插槽 -->
                <!-- <router-link :to="{path:'/order/order/create'}">
                            <el-button type="success" size="mini" style="margin-right: 3px;">发布商品</el-button>
                        </router-link> -->
                <el-button type="warning" size="mini" @click="exportModel = true">导出数据</el-button>
                <el-button type="danger" size="mini" @click="deleteALL">批量删除</el-button>
            </template>
            <!-- 高级搜索的表单 -->
            <template #form>
                <!-- 表单 -->
                <el-form inline ref="form" :model="form" label-width="70px">
                    <el-form-item label="订单编号" class="mb-0">
                        <el-input v-model="form.no" size="mini" placeholder="输入商品名称">

                        </el-input>
                    </el-form-item>
                    <!-- <el-form-item label="订单状态" class="mb-0">
                        <el-select v-model="form.type" style="height: 28px; line-height: 28px;" placeholder="选择订单状态">
                            <el-option label="区域一" value="shanghai">

                            </el-option>
                            <el-option label="区域二" value="beijing">

                            </el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="下单时间" class="mb-0">
                        <el-date-picker size='middle' v-model='form.time' type='daterange' range-separator='至'
                            start-placeholder='开始日期' end-placeholder='结束日期' value-format="yyyy-MM-dd">
                        </el-date-picker>
                    </el-form-item>

                    <el-form-item label="收货人" class="mb-0">
                        <el-input v-model="form.name" size="mini">

                        </el-input>
                    </el-form-item>
                    <el-form-item label="手机号" class="mb-0">
                        <el-input v-model="form.phone" size="mini">

                        </el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="info" size="mini" @click="searchEvent">搜索</el-button>
                        <el-button size="mini" @click="clearSearch">清空筛选条件</el-button>
                    </el-form-item>
                </el-form>
            </template>
        </button-search>
        <!-- 商品列表 -->
        <el-table :data="tableData" style="border: 1px; margin-top: 20px; background-color: antiquewhite;"
            @selection-change="handleSelectionChange">
            <!-- 添加顶部间距 -->
            <el-table-column type="selection" width="45" style="align-items: center;" />
            <el-table-column label="商品信息" width="330">
                <template slot-scope="scope">
                    <div class="d-flex">
                        <div style='flex:1'>
                            <p class="mb-1">订单编号</p>
                            <span class="mb-1"><small>{{ scope.row.no }}</small></span>
                        </div>
                        <div style='flex:1'>
                            <p class="mb-1">下单时间</p>
                            <span class="mb-1"><small>{{ scope.row.create_time }}</small></span>
                        </div>
                    </div>
                    <div class="media border-top py-2" v-for="(item, index) in scope.row.order_items" :key="index">
                        <img v-if="item.goods_item && item.goods_item.cover" :src="item.goods_item.cover"
                            style="width:60px; height:60px" class="mr-3" alt="...">
                        <div class="media-body">
                            <a class="mt-0 text-primary"> {{ scope.row.title }}</a>
                        </div>
                    </div>
                </template>
            </el-table-column>
            <el-table-column label="实付款" width='120' align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.total_price }}</span>
                    <p>(含运费￥0.00)</p>
                </template>
            </el-table-column>
            <el-table-column prop="sale_count" label="买家" width='120' align="center">
                <template slot-scope="scope">
                    <span>{{ scope.row.user ? scope.row.user.username : '-' }}</span>
                    <p>(用户id：{{ scope.row.user ? scope.row.user.id : '-' }})</p>
                </template>
            </el-table-column>
            <el-table-column label="商品状态" align="center">
                <template slot-scope="scope">
                    <span class="badge badge-success" v-if="scope.row.payment_method === 'wechat'">微信支付</span>
                    <span class="badge badge-primary" v-else-if="scope.row.payment_method === 'alipay'">支付宝支付</span>
                    <span class="badge badge-secondary" v-else>未支付</span>

                </template>
            </el-table-column>

            <el-table-column prop="stock" label="配送方式" align="center">
                <template slot-scope="scope" v-if="scope.row.ship_data">
                    <div>{{ scope.row.ship_data.express_company }}</div>
                    <div>{{ scope.row.ship_data.express_no }}</div>
                </template>
                <span class="badge badge-secondary" v-else>未配送</span>
            </el-table-column>
            <el-table-column prop="price" label="交易状态" align="center">
                <template slot-scope="scope">
                    <div>付款状态：<span :class="scope.row.payment_method ? 'badge-success' : ''">{{ scope.row.payment_method
                        ? '已付款' : '未付款' }}</span>
                    </div>
                    <div>发货状态：<span :class="scope.row.ship_data ? 'badge-success' : ''">{{ scope.row.ship_data ? '已发货' :
                        '待发货' }}</span>
                    </div>
                    <div>收货状态：<span
                            :class="scope.row.ship_status === 'received' ? 'badge-success' : 'badge-secondary'">{{
                                scope.row.ship_status
                                    === "received" ? '已收货' : '待收货' }}</span></div>
                </template>
            </el-table-column>
            <el-table-column prop="ischeck" label="操作" align="center" width="150">
                <template slot-scope="scope">
                    <!-- slot-scope="scope"创建了一个名为scope的新作用域，
                             它包含了子组件传递给插槽的所有数据。然后我们可以使用v-for指令来遍历scope.items。 -->
                    <el-button type="text" size="mini">订单详情</el-button>
                    <el-button type="text" size="mini" @click="ship(scope.row)"
                        v-if="scope.row.ship_status === 'pending' && scope.row.closed === 0 && scope.row.payment_method && scope.row.refund_status === 'pending'">订单发货</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 底部 -->
        <div style="height: 60px;">
            <el-footer class="border-top d-flex align-items-center px-0 position-fixed bg-white"
                style="bottom:0;left: 200px;right: 0; z-index: 100;">
                <!-- flex:1占剩余的所有空间 -->
                <div style="flex: 1;">
                    <el-pagination :current-change="page.current" :page-sizes="page.sizes" :page-size="page.size"
                        layout="total, sizes, prev, pager, next, jumper" :total="page.total"
                        @size-change="handleSizeChange" @current-change="handleCurrentChange">
                    </el-pagination>
                </div>
            </el-footer>

            <el-dialog title="订单发货" :visible.sync="shipModel" width="30%">
                <el-form :model="shipForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="快递公司" prop="express_company">
                        <el-select v-model="shipForm.express_company" placeholder="请选择快递公司">
                            <el-option v-for="(item, index) in express_company_options" :key="index" :label="item.name"
                                :value="item.name"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="快递单号" prop="express_no">
                        <el-input type="text" v-model="shipForm.express_no" autocomplete="off"></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="shipSubmit()">确定</el-button>
                        <el-button @click="resetForm('ruleForm')">重置</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>

            <el-dialog title="导出数据" :visible.sync="exportModel" width="40%">
                <el-form :model="exportForm" label-width="100px" class="demo-ruleForm">
                    <el-form-item label="订单类型" prop="tab">
                        <el-select v-model="shipForm.tab" placeholder="请选择">
                            <el-option v-for="(item, index) in tabBars" :key="index" :label="item.name"
                                :value="item.key"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="时间范围" prop="express_no">
                        <el-date-picker size='middle' v-model='exportForm.time' type='daterange' range-separator='至'
                            start-placeholder='开始日期' end-placeholder='结束日期'>
                        </el-date-picker>
                    </el-form-item>
                    <el-form-item>
                        <el-button type="primary" @click="exportModel = false">取消</el-button>
                        <el-button @click="exportExcel">确定</el-button>
                    </el-form-item>
                </el-form>
            </el-dialog>
        </div>
    </div>
</template>
<script>
import buttonSearch from '@/components/common/button-search.vue';
import common from '@/common/mixins/common';

export default {
    name: "orderList",
    mixins: [common],
    inject: ['layout'],
    components: { buttonSearch },
    data() {
        return {
            preUrl: 'order',

            tabIndex: 0,
            tabBars: [
                { name: "全部", key: 'all' },
                { name: "待付款", key: 'nopay' },
                { name: "待发货", key: 'noship' },
                { name: "已发货", key: 'shiped' },
                { name: "已收货", key: 'received' },
                { name: "已完成", key: 'finish' },
                { name: "已关闭", key: 'closed' },
                { name: "退款中", key: 'refunding' },
            ],
            form: {
                no: '',

                category: '',
                name: '',
                phone: '',
            },
            tableData: [],
            // multipleSelection: [],
            shipModel: false, // 发货弹窗
            shipForm: {
                express_company: '',
                express_no: '',
            },
            shipId: 0, // 发货订单ID
            express_company_options: [],

            exportModel: false,
            exportForm: {
                tab: '',
                time: ''
            }

        };
    },
    created() {
        // this.__getData();
        this.$axios.get('admin/express_company/1?limit=50', {
            token: true
        }).then(res => {
            // console.log('获取快递公司列表', res);
            let data = res.data.data;
            this.express_company_options = data.list;
        }).catch(err => {
            console.error('获取快递公司列表失败', err);
        })
    },
    computed: {
        tab() {
            return this.tabBars[this.tabIndex].key
        },
        params() {
            let str = '';
            for (let key in this.form) {
                let val = this.form[key];
                if (val) {
                    if (Array.isArray(val)) {
                        str += `&starttime=${val[0]}`;
                        str += `&endtime=${val[1]}`;
                    } else {
                        str += `&${key}=${val}`;
                    }
                }
            }
            return str;
        }
    },
    methods: {
        // 导出数据
        exportExcel() {
            if (this.exportForm.tab) {
                return this.$message.error('订单类型不能为空')
            }
            let url = `/admin/order/excelexport?tab=${this.exportForm.tab}`
            let params = ''
            let val = this.exportForm.time
            if (val && Array.isArray(val)) {

                params += `&starttime=${val[0]}`;
                params += `&endtime=${val[1]}`;

            }
            this.layout.showLoading()
            this.$axios.post(url + params, {}, {
                token: true,
                responseType:'blob'  //添加后便可以打开下载后的excel文件
            }).then((res) => {
                this.layout.hideLoading()
                this.exportModel=false
                if (res.status == 200) {
                    let url = window.URL.createObjectURL(new Blob([res.data]));
                    let link = document.createElement("a");
                    link.style.display = "none";
                    link.href = url;
                    let filename = new Date().getTime() + ".xlsx";
                    link.setAttribute("download", filename);
                    document.body.appendChild(link);
                    link.click();
                }

            }).catch(() => {
                this.layout.hideLoading()
            })
        },
        // 搜索
        getListUrl() {
            return `/admin/${this.preUrl}/${this.page.current}?limit=${this.page.size}&tab=${this.tab}${this.params}`;
        },
        // 处理获取列表结果
        getListResult(e) {
            // console.log(res);
            // console.log('获取列表结果', e);

            this.tableData = e.list;
        },
        // 生成数据
        // __getData() {
        //     for (let i = 0; i < this.tabBars.length; i++) {
        //         this.tableData.push({
        //             id: 1,
        //             title: '我们',
        //             cover: require('@/assets/image.png'),
        //             create_time: '2024-11-12',
        //             category: "专辑",
        //             type: '歌手专辑',
        //             sale_count: 23240,
        //             order: 2213,
        //             status: 1,
        //             stock: 28731,
        //             price: 279,
        //             ischeck: 1,
        //         })
        //     }
        // 0未审核，1审核通过，2不通过
        //     this.tableData.push({
        //         //让每一个选项卡都对应一个单独的页
        //         currentPage: 1,
        //         list: [],
        //     })
        //     for (let j = 0; j < 20; j++) {
        //         this.tableData[i].list.push({
        //             id: j,
        //             title: '我们' + i + '-' + j,
        //             cover: require('@/assets/image.png'),
        //             create_time: '2024-11-12',
        //             category: "专辑",
        //             type: '歌手专辑',
        //             sale_count: 23240,
        //             order: 2213,
        //             status: 1,
        //             stock: 28731,
        //             price: 279,
        //             ischeck: 1,
        //             // 0未审核，1审核通过，2不通过
        //         })
        //     }
        // }
        // },
        // 用来加载数据，监听点的是哪一个tab
        handleClick() {
            // console.log(this.activeName);
            this.getList()
        },
        // 清空筛选条件
        clearSearch() {
            this.form = {
                // name: '',
                no: '',
                // type: '',
                category: '',
                name: '',
                phone: '',
            }
            this.$refs.buttonSearch[this.tabIndex].closeSuperSearch();
        },
        // 搜索事件
        searchEvent(e = false) {
            // console.log('搜索事件', this.params);

            // 简单搜索,如果e有值
            if (typeof e === 'string') {
                // 将搜索的值赋值给this.form.no
                this.form.no = e;
                this.getList()
                // return console.log("简单搜索事件", e)
            }
            // 高级搜索事件
            // console.log("高级搜索")
            this.getList();
        },
        // handleSelectionChange(val) {
        //     this.multipleSelection = val;
        // },

        // // 删除当前商品
        // delItem(obj, index) {
        //     this.$confirm(obj.all ? '是否确定删除该选中所有的图片' : '是否删除图片', '提示', {
        //         confirmButtonText: '确定',
        //         cancelButtonText: '取消',
        //         type: 'warning'
        //     }).then(() => {
        //         this.tableData[this.tabIndex].list.splice(index, 1);
        //     })
        // },

        // 弹出发货弹窗
        ship(item) {
            this.shipId = item.id; // 记录发货订单ID
            this.shipModel = true;
            // 这里可以添加发货逻辑
            console.log('发货信息', item);
        },
        shipSubmit() {
            this.layout.showLoading();

            this.$axios.post('admin/order/' + this.shipId + '/ship', this.shipForm, {
                token: true,
            }).then(() => {
                this.$message.success('发货成功');
                this.layout.hideLoading();
                this.shipModel = false;
                this.getList();
            }).catch(err => {
                this.layout.hideLoading();
                console.error('发货失败', err);
                this.$message.error('发货失败，请稍后再试');
            });
        }
    },
};
</script>
<style scoped>
.text {
    font-size: 14px;
}

.item {
    margin-bottom: 18px;
}

.clearfix:before,
.clearfix:after {
    display: table;
    content: "";
}

.clearfix:after {
    clear: both
}
</style>